package com.activemq.demo;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.RedeliveryPolicy;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;

import javax.jms.ConnectionFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Administrator
 * @version 1.0
 * @description
 * @date 2019/7/2 17:54
 */
@Configuration
@Slf4j
@AutoConfigureAfter(ActiveMQAutoConfiguration.class)
public class ActiveMQConfig {

    @Bean
    public InitializingBean connectionFactory(ActiveMQConnectionFactory connectionFactory) {

        log.info("SET ConnectionFactory RedeliveryPolicy");
        log.info(connectionFactory.getBrokerURL());
        log.info(connectionFactory.getUserName());
        log.info(connectionFactory.getRedeliveryPolicy().getMaximumRedeliveries()+"");

        return () -> {
            RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
            //设置初始化重发延迟时间，默认1000毫秒
            redeliveryPolicy.setInitialRedeliveryDelay(1000);
            //设置最大重发次数，默认为6
            redeliveryPolicy.setMaximumRedeliveries(2);
            //是否开启重发延迟大小倍数递增，默认false
            redeliveryPolicy.setUseExponentialBackOff(true);
            //重发延迟递增倍数，默认为5
            redeliveryPolicy.setBackOffMultiplier(2);
            //这个参数主要是为了防止高并发下，消息重发会在同一时刻发生，让消息在时间上消费的更加均衡，默认为false
            redeliveryPolicy.setUseCollisionAvoidance(true);
            //设置下次重发延迟波动百分比，默认0.15，此处写成15是因为源码中对参数*0.01
            redeliveryPolicy.setCollisionAvoidancePercent((short)15);
            //设置最大重发延迟，默认为-1，表示无限增大
            redeliveryPolicy.setMaximumRedeliveryDelay(10000);

            connectionFactory.setRedeliveryPolicy(redeliveryPolicy);
        };
    }






}
